package GUI;

import java.awt.Font;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.Calendar;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import logic.Message;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.UIManager;

public class SearchBook extends JPanel{
	
	public final static int SEARCH = 1;
	public final static int SEARCH_FOR_DELETE = 2;
	public final static int SEARCH_FOR_UPDATE = 3;
	public final static int SEARCH_FOR_SEARCH_LOAN = 4;
	public final static int SEARCH_FOR_SEARCH_ORDER = 5;
	public final static int SEARCH_FOR_CREATE_ORDER = 6;
	public final static int SEARCH_FOR_CREATE_LOAN = 7;
	public final static int SEARCH_FOR_LATE_RETURN = 8;
	
	private Client_GUI parent;
	private JTextField textFieldBookName;
	private JTextField textFieldEdition;
	private JTextField textFieldDateOfPrinting;
	private JTextField textFieldDateOfPurchase;
	private JTextField textFieldPlaceInLibrary;
	private JTextField textFieldAuthors1;
	private JTextField textFieldAuthors2;
	private JTextField textFieldAuthors3;
	private JTextField textFieldAuthors4;
	
	
	private JLabel LBLBookName;
	private JLabel LBLDateOfPrinting;
	private JLabel LBLDateOfPurchase;
	private JLabel LBLEdition;
	private JLabel LBLPlaceInLibrary;
	private JLabel LBLAuthors1;
	private JLabel LBLAuthors2;
	private JLabel LBLAuthors3;
	private JLabel LBLAuthors4;
	private JLabel LBLCategory;
	private JLabel lblinput;

	private int Searchaction;
	
	//TODO set as private with getter
	public JPanel returnPanel;
	
	private ArrayList<String> categories;
	private JButton button;
	
	private SearchBook self;
	
	/**
	 * Constructor for SearchBook class
	 * @param parent - frame that wraps the JPanel
	 * @param action - The purpose which this class was called for (to search a book for loan,  order...)
	 * @param returnPanel - previous JPanel to redraw in case back clicked
	 */
	public SearchBook(final Client_GUI parent,final int action,final JPanel returnPanel) {
		this.parent = parent;
		this.self = this;
		this.setSize(Client_GUI.MAIN_WIDTH, Client_GUI.MAIN_HEIGHT);
		setLayout(null);
		this.setBackground(UIManager.getColor("inactiveCaption"));

		this.Searchaction = action;
		this.returnPanel = returnPanel;
		
		JLabel lblS = new JLabel("Search Book");
		lblS.setForeground(Color.RED);
		lblS.setFont(new Font("Tahoma", Font.BOLD, 17));
		lblS.setBounds(329, 11, 150, 28);
		add(lblS);
		
		JLabel lblBookName = new JLabel("Book Name:");
		lblBookName.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblBookName.setBounds(90, 103, 113, 14);
		add(lblBookName);
		
		JLabel lblEdition = new JLabel("Edition:");
		lblEdition.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblEdition.setBounds(90, 144, 113, 14);
		add(lblEdition);
		
		JLabel lblDateOfPurchase = new JLabel("Date of purchase:");
		lblDateOfPurchase.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblDateOfPurchase.setBounds(90, 222, 131, 14);
		add(lblDateOfPurchase);
		
		JLabel lblDateOfPrinting = new JLabel("Date of printing:");
		lblDateOfPrinting.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblDateOfPrinting.setBounds(90, 180, 131, 14);
		add(lblDateOfPrinting);
		
		JLabel lblPlaceInLibrary = new JLabel("Place in Library:");
		lblPlaceInLibrary.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblPlaceInLibrary.setBounds(90, 263, 131, 14);
		add(lblPlaceInLibrary);
		
		JLabel lblAuthors = new JLabel("Authors:");
		lblAuthors.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblAuthors.setBounds(476, 97, 131, 14);
		add(lblAuthors);
		
		JLabel lblCategory = new JLabel("Category:");
		lblCategory.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblCategory.setBounds(476, 220, 131, 14);
		add(lblCategory);
		
		textFieldBookName = new JTextField();
		textFieldBookName.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldBookName.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				parent.safeToClear =false ;
				ValidateData(false);
			}
		});
		textFieldBookName.setBounds(210, 97, 139, 20);
		add(textFieldBookName);
		textFieldBookName.setColumns(10);
		
		textFieldEdition = new JTextField();
		textFieldEdition.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				parent.safeToClear =false ;
				ValidateData(false);
			}
		});
		textFieldEdition.setColumns(10);
		textFieldEdition.setBounds(210, 138, 139, 20);
		add(textFieldEdition);
		
		textFieldDateOfPrinting = new JTextField();
		textFieldDateOfPrinting.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldDateOfPrinting.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				parent.safeToClear =false ;
				ValidateData(false);
			}
		});
		textFieldDateOfPrinting.setColumns(10);
		textFieldDateOfPrinting.setBounds(210, 178, 139, 20);
		add(textFieldDateOfPrinting);
		
		textFieldDateOfPurchase = new JTextField();
		textFieldDateOfPurchase.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldDateOfPurchase.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				parent.safeToClear = false ;
				ValidateData(false);
			}
		});
		textFieldDateOfPurchase.setColumns(10);
		textFieldDateOfPurchase.setBounds(210, 220, 139, 20);
		add(textFieldDateOfPurchase);
		
		textFieldPlaceInLibrary = new JTextField();
		textFieldPlaceInLibrary.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldPlaceInLibrary.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				parent.safeToClear = false ;
				ValidateData(false);
			}
		});
		textFieldPlaceInLibrary.setColumns(10);
		textFieldPlaceInLibrary.setBounds(210, 261, 139, 20);
		add(textFieldPlaceInLibrary);
		
		textFieldAuthors1 = new JTextField();
		textFieldAuthors1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldAuthors1.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				parent.safeToClear = false ;
				ValidateData(false);
				textFieldAuthors2.setVisible(true);
			}
		});
		textFieldAuthors1.setColumns(10);
		textFieldAuthors1.setBounds(571, 91, 139, 20);
		add(textFieldAuthors1);
		
		textFieldAuthors2 = new JTextField();
		textFieldAuthors2.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldAuthors2.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				ValidateData(false);
				textFieldAuthors3.setVisible(true);
			}
		});
		textFieldAuthors2.setColumns(10);
		textFieldAuthors2.setBounds(571, 122, 139, 20);
		add(textFieldAuthors2);
		textFieldAuthors2.setVisible(false);
		
		textFieldAuthors3 = new JTextField();
		textFieldAuthors3.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldAuthors3.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				ValidateData(false);
				textFieldAuthors4.setVisible(true);
			}
		});
		textFieldAuthors3.setColumns(10);
		textFieldAuthors3.setBounds(571, 153, 139, 20);
		add(textFieldAuthors3);
		textFieldAuthors3.setVisible(false);
		
		textFieldAuthors4 = new JTextField();
		textFieldAuthors4.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				lblinput.setVisible(false);
			}
		});
		textFieldAuthors4.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				ValidateData(false);
				
			}
		});
		textFieldAuthors4.setColumns(10);
		textFieldAuthors4.setBounds(571, 184, 139, 20);
		add(textFieldAuthors4);
		textFieldAuthors4.setVisible(false);
		
		JButton btnSearch = new JButton("Search");
		btnSearch.setFont(new Font("Tahoma", Font.BOLD, 13));
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				parent.safeToClear =false ;
				ValidateData(true);
			}
		});
		btnSearch.setBounds(167, 412, 150, 34);
		add(btnSearch);
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.setFont(new Font("Tahoma", Font.BOLD, 13));
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (returnPanel == null){
					parent.RepaintMenu(parent.client.Privelege);				
				}else{
					parent.RepaintMain(returnPanel);
				}
				

			}
		});
		btnCancel.setBounds(444, 412, 150, 34);
		add(btnCancel);
		
		LBLBookName = new JLabel("");
		LBLBookName.setBounds(358, 101, 20, 20);
		add(LBLBookName);
		
		LBLEdition = new JLabel("");
		LBLEdition.setBounds(359, 138, 20, 20);
		add(LBLEdition);
		
		LBLDateOfPrinting = new JLabel("");
		LBLDateOfPrinting.setBounds(359, 174, 20, 20);
		add(LBLDateOfPrinting);
		
		LBLDateOfPurchase = new JLabel("");
		LBLDateOfPurchase.setBounds(359, 223, 20, 20);
		add(LBLDateOfPurchase);
		
	    LBLPlaceInLibrary = new JLabel("");
		LBLPlaceInLibrary.setBounds(358, 264, 20, 20);
		add(LBLPlaceInLibrary);
		
		LBLAuthors1 = new JLabel("");
		LBLAuthors1.setBounds(720, 91, 20, 20);
		add(LBLAuthors1);
		
		LBLAuthors2 = new JLabel("");
		LBLAuthors2.setBounds(720, 122, 20, 20);
		add(LBLAuthors2);
		
		LBLAuthors3 = new JLabel("");
		LBLAuthors3.setBounds(720, 156, 20, 20);
		add(LBLAuthors3);
		
		LBLAuthors4 = new JLabel("");
		LBLAuthors4.setBounds(720, 187, 20, 20);
		add(LBLAuthors4);
		
		JLabel LBLCategory = new JLabel("");
		LBLCategory.setBounds(720, 221, 20, 20);
		add(LBLCategory);
		
		lblinput = new JLabel("You must give at least on input!!!");
		lblinput.setForeground(Color.RED);
		lblinput.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblinput.setBounds(286, 349, 236, 28);
		add(lblinput);
		
		categories = new ArrayList<String>();
		button = new JButton("Select");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
	
				CategorySelector cat = new CategorySelector(self,categories,1);

			}
		});
		button.setBounds(570, 219, 140, 23);
		add(button);
		lblinput.setVisible(false);
		
		if (returnPanel != null){
			btnCancel.setText("Back");
		}
		
	}
	
	
	public void SetCategories(ArrayList<String> cat){
		this.categories = cat;
		ValidateData(false);
	}
	
	
	
	
	private void ValidateData(boolean fromOK){
		
		ImageIcon okImageIcon = new ImageIcon(getClass().getClassLoader().getResource("resource/ok.png"));
		ImageIcon OK = new ImageIcon (okImageIcon.getImage().getScaledInstance(24, 24, java.awt.Image.SCALE_SMOOTH));
		
		ImageIcon badImageIcon = new ImageIcon(getClass().getClassLoader().getResource("resource/bad.png"));
		ImageIcon BAD = new ImageIcon (badImageIcon.getImage().getScaledInstance(24, 24, java.awt.Image.SCALE_SMOOTH));
		
		boolean valid = true;
		
		String temp; // the string to be tested on each test
		
		//Validate Book name
		if(!textFieldBookName.getText().equals("")) LBLBookName.setIcon(OK); 
		else LBLBookName.setIcon(null);
		
		if(!textFieldEdition.getText().equals("")&&textFieldBookName.getText().equals("")) 
			{
			valid = false;
			LBLEdition.setIcon(BAD); 
			}
		else if (!textFieldEdition.getText().equals("")&&!textFieldBookName.getText().equals("")) 
			{
			valid =true;
			LBLEdition.setIcon(OK);
			}
			else LBLEdition.setIcon(null);
		
		//validate printing date
		temp = textFieldDateOfPrinting.getText();
		if(temp.length()== 10)
		try
		{
			if ((temp.charAt(4) == '-' && temp.charAt(7) == '-') || (temp.charAt(4) == '/' && temp.charAt(7) == '/') || (temp.charAt(4) == '.' && temp.charAt(7) == '.')) 
				LBLDateOfPrinting.setIcon(OK);
			else {
				LBLDateOfPrinting.setIcon(BAD);
				valid = false;
			}
			
			int year = Integer.parseInt(temp.substring(0, 4));
			int month = Integer.parseInt(temp.substring(5, 7));
			int day = Integer.parseInt(temp.substring(8, temp.length()));

			Calendar validator = Calendar.getInstance();
			validator.set(year, month-1, day);
			validator.setLenient(false);
			validator.getTime();
			
		}catch(NumberFormatException e){
			LBLDateOfPrinting.setIcon(BAD);
			valid = false;
		}catch(Exception e){
			LBLDateOfPrinting.setIcon(BAD);
			valid = false;
		}
		else if(!temp.equals("")) {
			LBLDateOfPrinting.setIcon(BAD);
			valid = false;
		}
		else LBLDateOfPrinting.setIcon(null);
		
		
		//validate buying  date
		temp =textFieldDateOfPurchase.getText();
		if(temp.length()== 10)
			try
			{
				if ((temp.charAt(4) == '-' && temp.charAt(7) == '-') || (temp.charAt(4) == '/' && temp.charAt(7) == '/') || (temp.charAt(4) == '.' && temp.charAt(7) == '.')) 
					LBLDateOfPurchase.setIcon(OK);
				else {
					LBLDateOfPurchase.setIcon(BAD);
					valid = false;
				}
				
				int year = Integer.parseInt(temp.substring(0, 4));
				int month = Integer.parseInt(temp.substring(5, 7));
				int day = Integer.parseInt(temp.substring(8, temp.length()));

				Calendar validator = Calendar.getInstance();
				validator.set(year, month-1, day);
				validator.setLenient(false);
				validator.getTime();
				
			}catch(NumberFormatException e){
				LBLDateOfPurchase.setIcon(BAD);
				valid = false;
			}catch(Exception e){
				LBLDateOfPurchase.setIcon(BAD);
				valid = false;
			}
			else if(!temp.equals("")) {
				LBLDateOfPurchase.setIcon(BAD);
				valid = false;
			}
			else LBLDateOfPurchase.setIcon(null);
		
		
		//Validate author1 name
		if(!textFieldAuthors1.getText().equals("")) LBLAuthors1.setIcon(OK); 
		else LBLAuthors1.setIcon(null);
		
		//Validate author2 name
		if(!textFieldAuthors2.getText().equals("")) LBLAuthors2.setIcon(OK); 
		else LBLAuthors2.setIcon(null);
		
		//Validate author3 name
		if(!textFieldAuthors3.getText().equals("")) LBLAuthors3.setIcon(OK); 
		else LBLAuthors3.setIcon(null);
		
		//Validate author4 name
		if(!textFieldAuthors4.getText().equals("")) LBLAuthors4.setIcon(OK); 
		else LBLAuthors4.setIcon(null);
		
		temp = textFieldPlaceInLibrary.getText();
		String temp1 = temp.substring(temp.indexOf("-")+1, temp.length());
		if(!temp.endsWith(""))
		
			try
			{
				if (temp.indexOf("-")==-1 ||  temp.substring(0,temp.indexOf("-")-1).equals ("") || temp1.equals("")) 
				{
					LBLPlaceInLibrary.setIcon(BAD);
					valid = false;
				}
				else
				{
					Integer.parseInt(temp1);
					LBLPlaceInLibrary.setIcon(OK);
				}
			}
		catch (NumberFormatException e){
			LBLPlaceInLibrary.setIcon(BAD);
			valid = false;
			
		}
		
		
		
		if (fromOK){
			if (textFieldBookName.getText().equals("")&& !textFieldEdition.getText().equals("")){
				LBLBookName.setIcon(BAD);
				valid = false;
			}
			if (textFieldDateOfPrinting.getText().equals("")&& textFieldDateOfPurchase.getText().equals("")&& 
					textFieldPlaceInLibrary.getText().equals("")&& textFieldAuthors1.getText().equals("") && 
					textFieldBookName.getText().equals("") ){
				lblinput.setVisible(true);
				
				valid = false;
			}
			if(categories.size() > 0){
				valid = true;
				lblinput.setVisible(false);

			}
		}
		
		
		if (valid && fromOK){
			ArrayList<String> index = new ArrayList<String>();
			ArrayList<Object> data = new ArrayList<Object>();
			
			index.add("DIRECTOR");
			data.add(this.Searchaction);
			
			if(!textFieldBookName.getText().equals(""))
			{
				index.add("NAME");
				data.add(textFieldBookName.getText());
				
			}
			if(!textFieldEdition.getText().equals(""))
			{
				index.add("EDITION");
				data.add(textFieldEdition.getText());
				
			}
			if(!textFieldDateOfPrinting.getText().equals(""))
			{
				index.add("PRINT_DATE");
				data.add(textFieldDateOfPrinting.getText());
				
			}
			if(!textFieldDateOfPurchase.getText().equals(""))
			{
				index.add("PURCHASE_DATE");
				data.add(textFieldDateOfPurchase.getText());
				
			}
			if(!textFieldPlaceInLibrary.getText().equals(""))
			{
				index.add("LOCATION");
				data.add(textFieldPlaceInLibrary.getText());
				
			}
		
			ArrayList<String> authorList = new ArrayList<String>();
			if(!textFieldAuthors1.getText().equals("")) authorList.add(textFieldAuthors1.getText());
			if(!textFieldAuthors2.getText().equals("")) authorList.add(textFieldAuthors2.getText());
			if(!textFieldAuthors3.getText().equals("")) authorList.add(textFieldAuthors3.getText());
			if(!textFieldAuthors4.getText().equals("")) authorList.add(textFieldAuthors4.getText());
			String author = "";
			if (authorList.size() > 0){
				author = " AUTHOR LIKE '%" + authorList.get(0) + "%'";
				for(int i=1; i< authorList.size(); i++){
					author += " AND AUTHOR LIKE '%" + authorList.get(i) + "%'";
				}
			}
			
			
			index.add("AUTHORS");
			data.add(author);
			
	
			index.add("CATEGORIES");
			data.add(categories);
			
			
			int action = Message.SEARCH_BOOK_REQUEST;
			
			Message toSend = new Message(index, data, action);
			
			if (parent.sendMessageToServer(toSend) == 1){//message sent successfully
				parent.SetLoading(true);
				
				//TODO handle accept request on server side, and then sent result
				
			}else{//message send failed
				//TODO verify extream situation
			}
			
		
	}

	
}
}
